"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 主节点表文件损坏
Create At   : 2020/07/20
@zou_jialiang0505328114
Description :
    步骤 1.启动主备数据库，判断数据库状态；
    步骤 2.主机表文件内容清空
    步骤 3.重启主备机（主备机任意一台执行重启）；
    步骤 4.查询相关数据表；
Expect      :
    1、启动成功，状态正常
    2、执行成功
    3、执行成功
    4、主机查询结果为0，备机查询结果正常
History     :
    2021/1/14 n@ningyali 因该用例执行过程中会hung住，但并非bug，因此优化该用例
    2021/1/20 @peilinqian 清空表文件后，查询主机数据量结果不一定，导致用例概率性断言失败，增加初始插入数据后主备同步等待
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class Deletaduit(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    commonshsta = CommonSH('Standby1DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.common = Common('PrimaryRoot')
        self.log.info('----Opengauss_Reliability_Dbsys_Case193.py start----')
        self.dbPrimaryDbUser = Node(node='PrimaryDbUser')
        self.dbStandby1DbUser = Node(node='Standby1DbUser')
        self.Constant = Constant()
        self.T_NAME = 'reliability_dbsys193'
        self.TABLE_PATH = ''
        self.INSERT_NUM = 100000

    def test_startdb(self):
        self.log.info('----创建数据表，并插入数据----')
        result = self.common.createLargeNumTable(self.dbPrimaryDbUser,
                                                 self.T_NAME, 1,
                                                 self.INSERT_NUM)
        self.log.info(result)
        self.assertIn(self.Constant.CREATE_TABLE_SUCCESS, result)
        self.assertIn('INSERT 0 100000', result)

        self.log.info('----等待主备同步----')
        self.commonshpri.check_location_consistency('primary', 3)

        self.log.info('----查询表文件路径----')
        o_id = self.commonshpri.executDbSql(
            f'select oid from pg_class where relname=\'{self.T_NAME}\';')
        self.log.info(o_id)
        oid = o_id.splitlines()[-2]
        self.log.info(oid)
        result = self.commonshpri.executDbSql(
            f'Select pg_relation_filepath({oid}::regclass);')
        self.log.info(result)
        indexpath_tmp = result.splitlines()[-2].strip()
        self.TABLE_PATH = os.path.join(macro.DB_INSTANCE_PATH, indexpath_tmp)
        self.log.info(f'table path is: {self.TABLE_PATH}')

        self.log.info('----清空主机表文件内容----')
        empty_cmd = f'> {self.TABLE_PATH}'
        self.log.info(empty_cmd)
        result = self.dbPrimaryDbUser.sh(empty_cmd).result()
        self.log.info(result)

        ls_cmd = f"ls -l {self.TABLE_PATH}|tr -s ' '|cut -d' ' -f 5"
        self.log.info(ls_cmd)
        result = self.dbPrimaryDbUser.sh(ls_cmd).result()
        self.log.info(result)
        self.assertEqual(result, '0')

        sql_cmd = f'select count(*) from {self.T_NAME};'
        self.log.info(sql_cmd)
        result = self.commonshpri.executDbSql(sql_cmd)
        self.log.info("primary: " + result)

        self.log.info('查询数据库状态')
        status = self.commonshpri.getDbClusterStatus("status")
        self.log.info(status)

        self.log.info('----重启数据库，以清除缓存----')
        result = self.commonshpri.stopDbCluster()
        self.assertTrue(result)
        result = self.commonshpri.startDbCluster()
        self.assertTrue(result)

        self.log.info('查询数据库状态')
        status = self.commonshpri.getDbClusterStatus("status")
        self.log.info(status)

        self.log.info('----查询主备数据库对应表数据----')
        sql_cmd = f'select count(*) from {self.T_NAME};'
        self.log.info(sql_cmd)
        result = self.commonshpri.executDbSql(sql_cmd)
        self.log.info("primary: " + result)
        self.assertEqual(result.splitlines()[-2].strip(), '0')
        result = self.commonshsta.executDbSql(sql_cmd)
        self.log.info("standby1: " + result)
        self.assertIn(result.splitlines()[-2].strip(), str(self.INSERT_NUM))

    def tearDown(self):
        self.log.info('----this is tearDown----')
        self.log.info('----drop table----')
        result = self.commonshpri.executDbSql(
            f'drop table if exists {self.T_NAME} ;')
        self.log.info(result)
        self.log.info('----reliability_dbsys193.py finish----')
